package com.rpframework.module.common.bottom.quartz;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.rpframework.module.common.bottom.entity.Token;
import com.rpframework.module.common.bottom.service.TokenService;
import com.rpframework.module.common.bottom.weixin.AccessToken;
import com.rpframework.module.common.bottom.weixin.JsapiTicket;
import com.rpframework.module.common.bottom.weixin.util.WeixinUtil;
import com.rpframework.module.common.config.WeixinConfig;

/**
 * 微信令牌更新
 * Created by jump on 2016/7/17.
 */
public class WeiXinToken {

    private final Logger LOG = LoggerFactory.getLogger(getClass());

    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private WeixinConfig WeixinConfig;
    

    public void execute() {
        try {
            JsapiTicket jsapiTicket;
            AccessToken accessToken = WeixinUtil.getAccessToken(WeixinConfig.getAppId(), WeixinConfig.getAppSecret());
            jsapiTicket = WeixinUtil.getJsapiTicket(accessToken.getToken());
            if (null != jsapiTicket) {
                // 把access_token放到数据库中
                Token token = new Token();
                token.setAccessToken(accessToken.getToken());
                token.setTicket(jsapiTicket.getTicket());
                token.setAppId(WeixinConfig.getAppId());
                boolean updateByExampleSelective = tokenService.insertTS(token);
                if (updateByExampleSelective) {
                    LOG.info("获取access_token和js_api_ticket成功，有效时长{}秒",
                            accessToken.getExpiresIn());
                } else {
                    LOG.error("插入数据库失败");
                }
            }
        } catch (Exception ignored) {
            LOG.error("入数据库失败", ignored);
        }
    }
}